package com.huike.clues.service.impl;


import com.huike.clues.domain.TbClue;
import com.huike.clues.domain.TbClueTrackRecord;
import com.huike.clues.domain.vo.ClueTrackRecordVo;
import com.huike.clues.mapper.TbClueMapper;
import com.huike.clues.mapper.TbClueTrackRecordMapper;
import com.huike.clues.service.ITbClueTrackRecordService;
import com.huike.common.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.huike.common.utils.DateUtils.getNowDate;

/**
 * 线索跟进记录Service业务层处理
 * @date 2022-04-22
 */
@Service
public class TbClueTrackRecordServiceImpl implements ITbClueTrackRecordService {

    @Autowired
    private TbClueTrackRecordMapper tbClueTrackRecordMapper;
    @Autowired
    private TbClueMapper tbClueMapper;
    @Override
    public List<TbClueTrackRecord> list(Long clueId) {
        return tbClueTrackRecordMapper.list(clueId);
    }

    @Override
    @Transactional
    public int add(ClueTrackRecordVo tbClueTrackRecord) {
        TbClue tbClue = new TbClue();
        tbClue.setStatus("2");
        tbClue.setId(tbClueTrackRecord.getClueId());
        int i = tbClueMapper.updateTbClue(tbClue);
        if (i!=0){
            tbClueTrackRecord.setCreateTime(new Date());
            tbClueTrackRecord.setCreateBy(SecurityUtils.getUsername());
            Integer add = tbClueTrackRecordMapper.add(tbClueTrackRecord);
            if (add!=0){
                return add;
            }
        }
        return /*tbClueMapper.updateTbClue(tbClue)!=0?tbClueMapper.add(tbClueTrackRecord):*/0;
    }

    @Override
    @Transactional
    public int falses(Long id, String reason, String remark) {
        TbClue clue = tbClueMapper.selectTbClueById(id);
        int falseCount = clue.getFalseCount();

        ClueTrackRecordVo tbClueTrackRecord = new ClueTrackRecordVo();
        tbClueTrackRecord.setClueId(id);
        tbClueTrackRecord.setType("1");
        tbClueTrackRecord.setFalseReason(reason);
        tbClueTrackRecord.setCreateTime(getNowDate());
        tbClueTrackRecord.setRemark(remark);
        tbClueTrackRecord.setCreateBy(SecurityUtils.getUsername());

        if(falseCount <2){
            int i = falseCount + 1;
            clue.setFalseCount(i);
            clue.setStatus("4");
            clue.setUpdateTime(getNowDate());
            tbClueMapper.updateTbClue(clue);

            tbClueTrackRecord.setRecord("伪线索");
            return tbClueTrackRecordMapper.add(tbClueTrackRecord);
        }

        tbClueTrackRecord.setRecord("伪线索+满3次,已被删除");
        tbClueTrackRecordMapper.add(tbClueTrackRecord);
        return tbClueMapper.deleteTbClueById(id);
    }
}
